/**
 * @(#)basicView.js 0.3.0 2018-01-17
 * Copyright (c) 2017, YUNXI. All rights reserved.
 * YUNXI PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
import React, { Component } from 'react'
import { connect } from 'dva'
import cx from 'classnames'
import styles from './couponBasicStyle.less'
import { message, Row, Col, Select, Input, Form, Radio, Checkbox, Button, Table, Icon, DatePicker, InputNumber, Popconfirm, Modal, Cascader, Tooltip } from 'antd'
import { get, cloneDeep } from "lodash";
import { request } from "config/request";
import config from "config/config";
import { Link, hashHistory } from 'dva/router';
import $ from 'jquery';
import moment from 'moment';
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import PopUpSelect from 'widget/PopUpSelectnoModal/PopUpSelect'
import { isNullOrUndefined } from 'util';
const FormItem = Form.Item
const { Option } = Select
const RadioGroup = Radio.Group
const { TextArea } = Input
const CheckboxGroup = Checkbox.Group;
const { RangePicker } = DatePicker;
const formItemLayout = {
	labelCol: { span: 5 },
	wrapperCol: { span: 19 },
}
const tipsLayout = {
	labelCol: { span: 5 },
	wrapperCol: { span: 5 },
}
const ColLayout = {
	md: { span: 20 },
}
const tipText = '普通场景（上架后可直接领取），上架后，在美房详情中显示，可直接领取；拼团场景（拼团成功后可领取），需要完成拼团成功后，在活动显示或者自动发放到我的优惠券中'



const CouponBasicView = function ({ dispatch, model, form }) {

	const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form

	const { namespace, modelObj } = model
console.log('modelObj',modelObj)
	let { detail, areaList, estateList, indeterminate, checkAll,selectItem } = modelObj
	//console.log(moment().add(10, 'minutes'))
	const sellerTableColumn = [
		{ title: '项目名称', width: 100, dataIndex: 'productName', key: 'productId',render:(e,item)=>{
			return item.name
		} },
		{ title: '所属城市',width:200, dataIndex: 'city', key: 'city' ,render:(a, item, index, d, e, f)=>{
			//console.log(item)
			let arr = ['北京市','重庆','上海','天津']
			if(arr.indexOf(item.provinceName)>-1){
				return `${item.cityName}`
			  }else{
				return `${item.provinceName||''}${item.provinceName&&item.cityName&&' - '||''}${item.cityName||''}`
			  }
		  }},
		
	];
	
	let sellerQueryList = [
		// {name: '区域公司', type: 'select', key: 'regionId',list:addressList,notNeedAll:true},
		{ name: '省市', type: 'cascader', list: cloneDeep(areaList), key: ['province', 'city', 'county'], value: '' },
		{ name: '项目名称', type: 'text', key: 'name', value: '' },
	];
	
	const sellerSelectedColumn = [
		{ title: '项目名称', width: 110, dataIndex: 'productName', key: 'productId' ,render:(e,item)=>{
			return  item.productName ||item.name
		}},
		{ title: '所属城市', dataIndex: 'cityName', key: 'cityName',render:(a, item, index, d, e, f)=>{
			//console.log(item)
			// console.log(item)
			let arr = ['北京','重庆','上海','天津']
			let provinceName=''
			let cityName=''
			// console.log(areaList.length)
			for(let i=1;i<areaList.length;i++){
				if(item.province==areaList[i].value){
					provinceName=areaList[i].label
					if(arr.indexOf(provinceName)>-1){
						provinceName=''
					}
					for(let j=0;j<areaList[i].children.length;j++){
						if(item.city==areaList[i].children[j].value){
							cityName=areaList[i].children[j].label
							// console.log(provinceName,cityName)
							return <span>{`${provinceName}${provinceName && '-'}${cityName}`}</span>
						}
					}
				}
			}
			
		  }},
		
		 
	];

	const checkName = (rule, value, callback) => {
		let reg = new RegExp(/^1\d{10}$/);
		if (value && !(value).trim()) {
			callback('优惠券名称不能为空')
		} else {
			callback();
		}
	}

	const checkRemark = (rule, value, callback) => {
		let reg = new RegExp(/^1\d{10}$/);
		if (value && !(value).trim()) {
			callback('使用规则描述不能为空')
		} else {
			callback();
		}
	}

	const checkOfflineTime = (rule, value, callback) => {
		if (detail.onlineTime && value && detail.onlineTime > value.format('YYYY-MM-DD HH:mm:ss')) {
			return callback('下架时间不能早于上架时间')
		}
		callback();
	}

	function checkAllChange(e) {
		resetFields();
		let resData = cloneDeep(detail);
		if (e.target.checked) {
			let all = []
			estateList && estateList.forEach((e, i) => {
				all.push(e.productId + '')
			})
			resData.productIds = all
		} else {
			resData.productIds = []
		}
		dispatch({
			type: `${namespace}/updateStore`, payload: {
				indeterminate: false,
				checkAll: e.target.checked,
				detail: resData
			}
		})
	}

	function checkAllChangeBack(value) {
		let all = []
		estateList && estateList.forEach((e, i) => {
			all.push(e.productId + '')
		})
		dispatch({
			type: `${namespace}/updateStore`, payload: {
				indeterminate: !!value.length && (value.length < all.length),
				checkAll: value.length === all.length
			}
		})
	}

	function inputChange(key, value) {
		resetFields();

		let resData = cloneDeep(detail);

		if (key === 'couponValidTime') {
			resData.startTime = value[0] ? value[0] : '';
			resData.expireDate = value[1] ? value[1] : '';
		} else if (key === 'city') {
			resData.province = value[0] ? value[0] : '';
			resData.city = value[1] ? value[1] : '';
			//重置楼盘项目列表选中数据
			resData.productIds = [];
			modelObj.checkAll = false;
			modelObj.indeterminate = false;
		} else {
			console.log(key);
			console.log('..........',value)
			resData[key] = value;
		}

		dispatch({ type: `${namespace}/updateStore`, payload: { detail: resData } });
	}

	return (
		<div className="public_listMain">
			<CollapsiblePanels title={!!detail.couponsConfigId ? '编辑优惠券' : "创建优惠券"} hideUpDownBtn={true} className={styles.CouponBasic}>
				<Form>
				<Row>
						<Col {...ColLayout} style={{position:'relative'}}>
							<FormItem {...formItemLayout} label="使用场景">
								{
									getFieldDecorator('scene', {
										rules: [
											{ required: true, message: '请选择使用场景' },
										],
										initialValue: detail.scene?detail.scene+'':''
									})
										(
										<Select
											placeholder='请选择使用场景'
											style={{ width: '300px' }}
											onChange={value => { inputChange('scene', value) }}
										>
											<Option value="">请选择</Option>
											<Option value="1">普通场景（上架后可直接领取）</Option>
											<Option value="2">拼团场景（拼团成功后可领取，集团专用）</Option>
											<Option value="3">活动场景（关联活动使用）</Option>
										</Select>
										)
								}
							</FormItem>
							<Col style={{position:'absolute',color:'rgb(0, 136, 204)',fontSize:'16px',top:'8px',left:'34rem',zIndex:99}}>
								<Tooltip title={tipText}><Icon type="question-circle" className='toopIcon' /></Tooltip>
							</Col>
						</Col>
					</Row>
					<Row>
						<Col {...ColLayout}>
							<FormItem {...formItemLayout} label="优惠券类型">
								{
									getFieldDecorator('type', {
										rules: [
											{ required: true, message: '请选择优惠券类型' },
										],
										initialValue: detail.type?detail.type+'':''
									})
										(
										<Select
											placeholder='请选择优惠券类型'
											style={{ width: '300px' }}
											onChange={value => { inputChange('type', value) }}
										>
											<Option value="">请选择</Option>
											<Option value="1">代金券</Option>
											<Option value="2">折扣券</Option>
										</Select>
										)
								}
							</FormItem>
						</Col>
					</Row>
					<Row>
						<Col {...ColLayout}>
							<FormItem label={'优惠券名称'} {...formItemLayout}>
								{
									getFieldDecorator('name', {
										rules: [
											{ required: true, message: `优惠券名称不能为空` },
											{ validator: checkName }
										],
										initialValue: detail.name || ''
									})
										(<Input
											style={{ width: '300px' }}
											placeholder={`请输入优惠券名称`}
											onChange={e => { inputChange('name', e.target.value) }}
										/>)
								}
							</FormItem>
						</Col>
					</Row>
					<Row>
						<Col {...ColLayout}>
							<FormItem label={'发放总数'} {...formItemLayout}>
								{
									getFieldDecorator('circulation', {
										rules: [
											{ required: true, message: `发放总数不能为空` },
										],
										initialValue: detail.circulation
									})
										(<InputNumber
											max={99999999}
											min={1}
											precision={0}
											style={{ width: '100px' }}
											onChange={value => { inputChange('circulation', value) }}
										/>)
								}
								<span style={{ display: 'inline-block', marginLeft: 8 }}>张</span>
							</FormItem>
						</Col>
					</Row>
					{
						detail.type && <Row>
							<Col {...ColLayout}>
								<FormItem label={detail.type == 1 ? '优惠券金额' : '折扣'} {...formItemLayout}>
									{
										getFieldDecorator('amount', {
											rules: [
												{ required: true, message: `不能为空` },
											],
											initialValue: detail.amount
										})
											(<InputNumber
												max={detail.type == 1 ? 99999999 : 0.99}
												min={detail.type == 1 ? 1 : 0.01}
												precision={detail.type == 1 ? 0 : 2}
												// step={0.01}
												style={{ width: '100px' }}
												onChange={value => { inputChange('amount', value) }}
											/>)
									}
								</FormItem>
							</Col>
						</Row>
					}

					{/* <Row>
						<Col {...ColLayout}>
							<FormItem label={'所属城市'} {...formItemLayout}>
								{getFieldDecorator('city', {
									initialValue: detail && detail.province && detail.city ? [detail.province + '', detail.city + ''] : '',
									rules: [
										// {
										// 	type: 'array',
										// 	// required: true,
										// 	message: '请选择所属城市',
										// }
									],
								})(<Cascader style={{ width: '300px' }} options={areaList} placeholder="请选择"
									onChange={(value) => {
										inputChange('city', value)
										dispatch({ type: `${namespace}/getCityEstateList`, payload: { params: { province: value[0], city: value[1] } } })
									}} />)}(所属城市为空则搜索全国范围项目)
							</FormItem>
						</Col>
					</Row>
					<Row>
						<Col {...ColLayout}>
							<FormItem label={'市楼盘项目列表'} {...formItemLayout}>
								{<div className={styles.resetCheckbox}>
									<Checkbox
										indeterminate={indeterminate}
										checked={checkAll}
										onChange={(e) => { checkAllChange(e) }}
									>全选</Checkbox>
								</div>}
								{
									getFieldDecorator('productIds', {
										rules: [
											{ required: true, message: `请选择市楼盘项目列表` },
										],
										initialValue: detail.productIds || []
									})
										(<CheckboxGroup options={estateList}
											onChange={(value) => {
												inputChange('productIds', value)
												checkAllChangeBack(value)
											}}
										/>)
								}
							</FormItem>
						</Col>
					</Row> */}
					<CollapsiblePanels title="添加楼盘" hideUpDownBtn={true} >
                <PopUpSelect
                    tableColumn={sellerTableColumn}
                    selectedColumn={sellerSelectedColumn}
                    selectedTableScroll={{ x: 420 }}
                    queryList={cloneDeep(sellerQueryList)}
                    isSave={true}
                    refreshByEnter={true}
                    requestUrl='admin/estate/adminList'
                    title='选择工程名称'
                    respListKey='rows'
                    idKey='productId'
                    onItem={selectItem}
                    onChange={(e) => {
                        let productIds=[]
                        e.map((item)=>{
                            productIds.push(item.productId)
                        })
						detail.productIds=Array.from(new Set(productIds))
						console.log(e)
                        dispatch({
                            type: `${namespace}/updateStore`,
                            payload: {detail,selectItem:e}
                        })
                    }}
                ></PopUpSelect>
            </CollapsiblePanels>
					<Row>
						<Col {...ColLayout}>
							<FormItem label={'每个账号可领取上限'} {...formItemLayout}>
								{
									getFieldDecorator('accountLimit', {
										rules: [
											{ required: true, message: `每个账号可领取上限不能为空` },
										],
										initialValue: detail.accountLimit?detail.accountLimit:'1'
									})
										(<InputNumber
											min={1}
											precision={0}
											style={{ width: '100px' }}
											onChange={value => { inputChange('accountLimit', value) }}
										/>)
								}
								{/* <Icon style={{marginLeft:'20px',marginRight:'10px',color:'red'}} type="exclamation-circle" theme="filled" /> */}
								{/* <span >如果设置为0则无限领取</span> */}
							</FormItem>
						</Col>
					</Row>
					<Row>
						<Col {...ColLayout}>
							<FormItem label={'每个账号每天可领取上限'} {...formItemLayout}>
								{
									getFieldDecorator('accountDayLimit', {
										rules: [
											{ required: true, message: `每个账号每天可领取上限不能为空` },
										],
										initialValue: detail.accountDayLimit?detail.accountDayLimit:'1'
									})
										(<InputNumber
											min={1}
											precision={0}
											style={{ width: '100px' }}
											onChange={value => { inputChange('accountDayLimit', value) }}
										/>)
								}
								{/* <Icon style={{marginLeft:'20px',marginRight:'10px',color:'red'}} type="exclamation-circle" theme="filled" /> */}
								{/* <span >如果设置为0则无限领取</span> */}
							</FormItem>
						</Col>
					</Row>
					<Row>
						<Col {...ColLayout}>
							<FormItem label={'上架时间'} {...formItemLayout}>
								{
									getFieldDecorator('onlineTime', {
										rules: [
											{ required: true, message: `上架时间不能为空` },
										],
										initialValue: detail.onlineTime ? moment(detail.onlineTime, 'YYYY-MM-DD HH:mm:ss') : null
									})
										(<DatePicker style={{ width: '300px' }}
											showTime
											format="YYYY-MM-DD HH:mm:ss"
											onChange={(date, dateString) => { inputChange('onlineTime', dateString) }}
										/>)
								}
							</FormItem>
						</Col>
					</Row>
					<Row>
						<Col {...ColLayout}>
							<FormItem label={'下架时间'} {...formItemLayout}>
								{
									getFieldDecorator('offlineTime', {
										rules: [
											{ required: true, message: `下架时间不能为空` },
											{ validator: checkOfflineTime }
										],
										initialValue: detail.offlineTime ? moment(detail.offlineTime, 'YYYY-MM-DD HH:mm:ss') : null
									})
										(<DatePicker style={{ width: '300px' }}
											showTime
											format="YYYY-MM-DD HH:mm:ss"
											onChange={(date, dateString) => { 
												//inputChange('offlineTime', dateString) 
												// 同步下架时间与结束时间
												var now = moment().locale('zh-cn').format('YYYY-MM-DD HH:mm:ss');
												detail.offlineTime =  dateString
												detail.startTime = now
												dispatch({
													type:`${namespace}/updateStore`,
													payload:{	
														detail
													}
												})
												// setFieldsValue({
												// 	"couponValidTime": [moment(detail.startTime, 'YYYY-MM-DD HH:mm:ss'), moment(detail.expireDate, 'YYYY-MM-DD HH:mm:ss')]
												// })
												// resetFields(['couponValidTime'])
											}}
										/>)
								}
							</FormItem>
						</Col>
					</Row>
					<Row>
						<Col {...ColLayout}>
							<FormItem label={'优惠券有效期'} {...formItemLayout}>
								{
									getFieldDecorator('couponValidTime', {
										rules: [
											{ required: true, message: `优惠券有效期不能为空` },
										],
										initialValue: detail && detail.startTime && detail.expireDate ? [moment(detail.startTime, 'YYYY-MM-DD HH:mm:ss'), moment(detail.expireDate, 'YYYY-MM-DD HH:mm:ss')] : []
									})
										(<RangePicker style={{ width: '300px' }}
											//disabled={true}
											showTime
											format="YYYY-MM-DD HH:mm:ss"
											onChange={(date, dateString) => { 
												inputChange('couponValidTime', dateString) 
												//同步下架时间与结束时间
												// detail.offlineTime =   dateString[1]
												// dispatch({
												// 	type:`${namespace}/updateStore`,
												// 	payload:{	
												// 		detail
												// 	}
												// })
											}}
										/>)
								}
							</FormItem>
						</Col>
					</Row>
					<Row>
						<Col {...ColLayout}>
							<FormItem label={'使用规则描述'} {...formItemLayout}>
								{
									getFieldDecorator('remark', {
										rules: [
											{ required: true, message: `使用规则描述不能为空` },
											{ validator: checkRemark }
										],
										initialValue: detail.remark || '',
									})
										(<TextArea style={{ height: 180 }}
											onChange={e => { inputChange('remark', e.target.value) }}
										/>)
								}
							</FormItem>
						</Col>
					</Row>
					<div className={styles.btn}>
						{/* <Button type="primary" style={{ marginRight: '20px' }} onClick={() => { dispatch({ type: `${namespace}/updateStore`, payload: { currentStep: 1 } }) }}>下一步</Button> */}
						<Button type="primary" style={{ marginRight: '20px' }}
							onClick={() => {
								validateFields((err, values) => {
									if (!err) {
										dispatch({ type: `${namespace}/submitCoupon` })
									}
								})
							}}>完成</Button>
						<Button onClick={() => {resetFields(); hashHistory.push('/home/infoAdmin/couponList') }}>取消</Button>
					</div>
				</Form>
			</CollapsiblePanels>
		</div>
	)

}

export default Form.create()(CouponBasicView)
